import { doLogin } from '@/api/user'
const state = {
  // 刷新页面时，状态管理器中的数据会丢失
  isLogin: localStorage.getItem('isLogin') === 'true',
  token: localStorage.getItem('token') || '',
  userid: localStorage.getItem('userid') || ''
}
const mutations = {
  changeIsLogin (state, payload) {
    state.isLogin = payload
  },
  changeToken (state, payload) {
    state.token = payload
  },
  changeUserid (state, payload) {
    state.userid = payload
  }
}
const actions = {
  loginAction (context, params) { // 处理登录的业务逻辑
    console.log(2)
    return new Promise((resolve, reject) => {
      doLogin(params).then(res => {
        console.log(3)
        if (res.data.code === '10010') {
          resolve(1)
        } else if (res.data.code === '10011') {
          resolve(2)
        } else {
          console.log(res.data.data)
          localStorage.setItem('token', res.data.data.token)
          localStorage.setItem('userid', res.data.data.userid)
          localStorage.setItem('isLogin', true)
          // 修改状态
          context.commit('changeIsLogin', true)
          context.commit('changeToken', res.data.data.token)
          context.commit('changeUserid', res.data.data.userid)
          resolve(3)
        }
      })
    })
  },
  logoutAction () { // 处理退出的业务逻辑

  }
}

export default {
  namespaced: true, // 命名空间的描述，防止多开发者命名的冲突问题
  state,
  mutations,
  actions
}
